package main

import "unsafe"

// text-mode VGA memory starts at 0xB8000
const vgaBase = uintptr(0xB8000)
const cols = 80

func vgaWriteString(row int, col int, s string, fg byte, bg byte) {
    if row < 0 { row = 0 }
    if row >= 25 { row = 24 }
    if col < 0 { col = 0 }
    if col >= cols { col = cols-1 }
    attr := (bg << 4) | (fg & 0x0F)
    off := uintptr((row*cols + col) * 2)
    for i := 0; i < len(s) && col+i < cols; i++ {
        *(*byte)(unsafe.Pointer(vgaBase + off + uintptr(i*2))) = s[i]
        *(*byte)(unsafe.Pointer(vgaBase + off + uintptr(i*2) + 1)) = attr
    }
}

// Provide C-style memory helpers that TinyGo runtime expects
//go:export memset
func memset(p unsafe.Pointer, c byte, n uintptr) unsafe.Pointer {
    base := uintptr(p)
    for i := uintptr(0); i < n; i++ {
        *(*byte)(unsafe.Pointer(base + i)) = c
    }
    return p
}

//go:export memcpy
func memcpy(dst unsafe.Pointer, src unsafe.Pointer, n uintptr) unsafe.Pointer {
    d := uintptr(dst)
    s := uintptr(src)
    for i := uintptr(0); i < n; i++ {
        *(*byte)(unsafe.Pointer(d + i)) = *(*byte)(unsafe.Pointer(s + i))
    }
    return dst
}

//go:export user_entry
func user_entry() {
    // Cyan on black
    vgaWriteString(2, 2, "Hello from TinyGo user program!", 0x0B, 0x00)
}